/*
 * pH Template class
 *
 * Options:
 *
 * dataURL:	data URL. Data should be a JSON Array.
 *
 */

jQuery.fn.pH_template = function(options)
{
	var options = jQuery.extend( {
		data: null, /* pH.Data Object  */
		on_ready: false
	}, options);

	var replace = function(content, data)
	{
		for (key in data)
		{
			content = content.replace("{" + key + "}", data[key]);
		}

		return content;
	};
	
	var populate = function(element, template, data)
	{
		var body = $(element).pH_body();
		body.empty();

		for (var i in data)
		{
			var div = document.createElement("DIV");
			div.innerHTML = replace(template, data[i]);

			body.append(div); 
		}


		if (options.on_ready) options.on_ready(element);

		$(element).trigger("update");
	};

	return this.each(function() {
		var element = this;

		// Look for Body
		var body = $(this).pH_body();

		var template = body.html();

		$(this).bind("populate", function(el, data)
		{
			populate(element, template, data);
		});

		$(options.data).bind("update", function(el, data)
		{
			$(element).trigger("populate", [data]);
		});

		options.data.get();
	});
};

